import { ElMessage } from 'element-plus';

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export const parseTime = (time: any, cFormat: any) => {
  if (time.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time *= 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const timeStr = format.replace(/{([ymdhisa])+}/g, (result: any, key: any) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return timeStr
}

/**
 *   从网页地址中截取参数
 *
 *   @param {string} name 截取的key值
 *   @return string || Json 如果传入key, 则返回(string)key对应的具体值；否则返回所有参数的键值对json
 */
export const getUrlValue = (name?: string) => {
  const search = decodeURI(window.location.href.split('?')[1])
  if (name) {
    if (!search) return ''
    const str = search.split(`${ name }=`)[1]
    return str ? str.split(/=+|&+|#\//)[0] : ''
  } 
  if (!search) return {}
  const datas = search.split(/=+|&+|#\//),
    len = datas.length - 1,
    result = {}
  for (let i = 0; i < len; i++) {
    if (i % 2) continue
    result[datas[i]] = datas[i + 1]
  }
  return result
}
/**
* 深拷贝数组/对象
*
* @param {Array/Object} source
*/
export const objDeepCopy = (source: any) => {
  if (!source) return undefined
  const sourceCopy = source instanceof Array ? [] : {}
  for (const item in source) {
    sourceCopy[item] = typeof source[item] === 'object' && source[item] !== null
      ? objDeepCopy(source[item])
      : source[item]
  }
  return sourceCopy
}
/**
* 清除对象空属性
* @param obj {Object} source
*/
export const cleanObj = (obj: any) => {
  const result = {}
  for (const propName in obj) {
    if (obj[propName] || obj[propName] === 0) {
      result[propName] = obj[propName]
    }
  }
  return result
}
/**
 * 获取图片完整url
 * @param {String} url
 */
export const getImage = (url: string | null, errorImage: string) => {
  if (url) {
    return import.meta.env.VITE_IMAGE_SERVICE_URL + url;
  }
  if (errorImage) {
    return new URL(errorImage, import.meta.url).href;
  }
  return new URL('../assets/images/error-image.png', import.meta.url).href;
};

/**
 * 复制页面值
 */ 
export const copyValue = async (value: string, msg: string | '') => {
  try {
    await navigator.clipboard.writeText(value);
    ElMessage.success(msg);
  } catch (err) {
    // 降级处理：使用传统的复制方法
    const textArea = document.createElement('textarea');
    textArea.value = value;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
    ElMessage.success(msg);
  }
};

/**
 * 对象类型单位映射
 */
export const getUsageUnit = (objectType: string) => {
  const unitMap: Record<string, string> = {
    '电表': 'kW·h',
    '水表': 't',
    '房租': '㎡'
  };
  return unitMap[objectType] || '';
};